package com.witframework.security;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.ObjectInputStream;

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
public class DecryptFile {
	public static InputStream decrypt(String keypath,String cipherPath) throws Exception {	   
	    return decrypt(new FileInputStream(keypath),new FileInputStream(cipherPath));
	}
	public static InputStream decrypt(InputStream keypath,InputStream cipherPath) throws Exception {
	    ObjectInputStream ois = new ObjectInputStream(keypath);
	    DESKeySpec ks = new DESKeySpec((byte[]) ois.readObject());
	    SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
	    SecretKey key = skf.generateSecret(ks);
	    Cipher c = Cipher.getInstance("DES/CFB8/NoPadding");
	    c.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec((byte[]) ois.readObject()));	   
	    CipherInputStream cis = new CipherInputStream(cipherPath, c);
	    return cis;
	}
	public static void decryptFile(String keypath,String cipherPath,String outPath) throws Exception {	   
		InputStream in=decrypt(new FileInputStream(keypath),new FileInputStream(cipherPath));
		FileOutputStream out=new FileOutputStream(outPath);
		byte[] buf=new byte[10240];
		int readSize=0;
		while( (readSize=in.read(buf))>0){
			out.write(buf,0,readSize);
		}
		out.close();
		in.close();
	}
	public static void decryptFile(String keypath,String cipherPath) throws Exception {	 
		decryptFile(keypath,cipherPath,cipherPath+".dec");
	}
	public static void decryptFile(String cipherPath) throws Exception {	 
		decryptFile(new File(cipherPath).getParent()+File.separator+"keyFile",cipherPath,cipherPath+".plain");
	}
	public static void main(String[] args) throws Exception {
		if (args.length == 0) {
			System.out.println("param error!");
		}
		if (args.length == 1) {
			decryptFile(args[0]);
		}
		if (args.length == 2) {
			decryptFile(args[0], args[1]);
		}
		if (args.length == 3) {
			decryptFile(args[0], args[1], args[2]);
		}
	}
}
